import { BadRequestException, HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectEntityManager } from '@nestjs/typeorm';
import { EntityManager } from 'typeorm';
import { FileEntity } from './entities/file.entity';

@Injectable()
export class FileService {
  @InjectEntityManager()
  private readonly entityManager: EntityManager

  async create(file: any) {
    if (!file) {
      throw new BadRequestException('No file uploaded')
    }
    
    const newFile = new FileEntity()
    newFile.originalName = file.originalname
    newFile.fileName = file.filename
    newFile.filePath = file.path
    newFile.mimetype = file.mimetype
    newFile.size = file.size
    newFile.url = `/static/uploads/${newFile.fileName}`

    await this.entityManager.save(FileEntity, newFile);

    return newFile.url;
  }

  async findAll(current: number, pageSize: number) {
    const pagesize = pageSize > 100 ? 100 : pageSize;
    const [list, total] = await this.entityManager.findAndCount(FileEntity, {
      take: pagesize,
      skip: (current - 1) * pagesize,
      order: { id: 'DESC' },
    }); // 查找所有
    return {
      list,
      total,
    };
  }

  async remove(id: number) {
    const [existOss] = await this.entityManager.findBy(FileEntity, { id });
    if (!existOss) {
      throw new HttpException(`id为${id}的文件不存在`, HttpStatus.BAD_REQUEST);
    }
    return this.entityManager.remove(FileEntity, existOss);
  }
}
